import cv2
import numpy as np
import matplotlib.pyplot as plt

# 读取图像并转换为二值图像
img = cv2.imread("plant.png", 0)
img_copy = img.copy()
_, img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

skel = np.zeros(img.shape, np.uint8)
temp = np.zeros(img.shape, np.uint8)

element = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))

done = False
process_imgs = {}

while not done:
    img_cp = img.copy()
    fg, ax = plt.subplots(1, 5, figsize=(20, 5))

    ax[0].imshow(img, cmap='gray')
    ax[0].set_title('Original Image')

    cv2.morphologyEx(img, cv2.MORPH_OPEN, element, temp)
    ax[1].imshow(temp, cmap='gray')
    ax[1].set_title('Open Operation')

    # 使用np.bitwise_not和np.bitwise_and模拟XOR操作
    temp_inv = np.bitwise_not(temp)  # 对temp取反
    white_points = np.bitwise_and(img_cp, temp_inv)  # 保留img_cp中temp_inv为白色的部分
    ax[2].imshow(white_points, cmap='gray')
    ax[2].set_title('Simulated XOR Operation')

    skel = cv2.bitwise_or(skel, white_points)
    ax[3].imshow(skel, cmap='gray')
    ax[3].set_title('OR Operation')

    img = cv2.erode(img, element)
    ax[4].imshow(img, cmap='gray')
    ax[4].set_title('Erode Operation')

    for a in ax:
        a.axis('off')
    plt.show()

    done = cv2.countNonZero(img) == 0

fig, ax = plt.subplots(1, 2, figsize=(10, 5))
ax[0].imshow(img_copy, cmap='gray')
ax[0].set_title('Original Image')
ax[0].axis('off')
ax[1].imshow(skel, cmap='gray')
ax[1].set_title('Skeleton Image')
ax[1].axis('off')
plt.show()